Skip to main content
ICT
Lesson A17 - Quadratic Sorting Algorithms
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

C. Selection Sort page 5 of 11

  1. The Selection Sort also makes several passes through the list. On each pass, it compares each remaining item to the smallest (or largest) item that has been found so far in the pass. In the example below, the Selection Sort method finds the smallest item on each pass. At the end of a pass, the smallest item found is swapped with the last remaining item for that pass. Thus, swapping only occurs once for each pass. Reducing the number of swaps makes the algorithm more efficient.

  2. The logic of Selection Sort is similar to Bubble Sort except that fewer swaps are executed.

    void selectionSort(ArrayList <Integer> list){
      int min, temp;

      for (int outer = 0; outer < list.size() - 1; outer++){
        min = outer;
        for (int inner = outer + 1; inner < list.size(); inner++){
          if (list.get(inner) < list.get(min)) {
            min = inner; // a new smallest item is found
          }
        }
        //swap list[outer] & list[min]
        temp = list.get(outer);
        list.set(outer, list.get(min));
        list.set(min, temp);
      }
    }

  1. Again, assuming that we have a list of 6 numbers, the outer loop will range from 1 to 5. When outer = 1, we will look for the smallest value in the list and move it to the first position in the array.

  2. However, when looking for the smallest value to place in position 1, we will not swap as we search through the list. The algorithm will check from indexes 1 to 5, keeping track of where the smallest value is found by saving the index of the smallest value in min. After we have found the location of the smallest value, we swap list[outer] and list[min].

  3. By keeping track of where the smallest value is located and swapping only once, we have a more efficient algorithm than Bubble Sort.

  4. Here is a small list of numbers to test your understanding of Selection Sort. Fill in the correct numbers for each line after the execution of the outer loop. (Answers are found in Lesson A17 Handout, Sorting Answers.)
outer
57
95
88
14
25
6
1
_____
_____
_____
_____
_____
_____
2
_____
_____
_____
_____
_____
_____
3
_____
_____
_____
_____
_____
_____
4
_____
_____
_____
_____
_____
_____
5
_____
_____
_____
_____
_____
_____

 

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.